package com.share.uesr.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.core.constant.MessageConstant;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.exception.ServiceException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.uesr.mapper.UserInfoMapper;
import com.share.uesr.service.IUserInfoService;


import com.share.user.domain.UpdateUserLogin;
import com.share.user.domain.UserCountVo;
import com.share.user.domain.UserInfo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户Service业务层处理
 *
 * @author suixin
 * @date 2025-03-31
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    /**
     * 查询用户列表
     *
     * @param userInfo 用户
     * @return 用户
     */
    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        return userInfoMapper.selectUserInfoList(userInfo);
    }


    /**
     * 小程序授权登录
     *
     * @param code
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public UserInfo wxLogin(String code) {
        //1 拿着code + 微信公众平台id  + 秘钥 请求微信接口服务，返回openid
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();

            //2 拿着openid查询数据库表，如果表里面没有openid值，表示第一次登录
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getWxOpenId, openid);
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);

            if (userInfo == null) {
                //添加用户信息到数据库表
                userInfo = new UserInfo();
                userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
                userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                userInfo.setWxOpenId(openid);
                userInfoMapper.insert(userInfo);
            }
            //3 返回userInfo用户信息
            return userInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 更新用户登录信息
     * @param updateUserLogin
     * @return
     */
    @Override
    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getUserId());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        userInfoMapper.updateById(userInfo);

        return true;
    }


    /**
     * 是否免压押金
     * @return
     */
    @Override
    public Boolean isFreeDeposit() {
        //微信支付分
        //https://pay.weixin.qq.com/wiki/doc/apiv3/payscore.php?chapter=18_1&index=2
        // 默认免押金，模拟实现
        //根据用户id查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(SecurityContextHolder.getUserId());
        //设置押金状态
        userInfo.setDepositStatus("1");
        userInfoMapper.updateById(userInfo);
        return true;
    }


    /**
     * 获取用户数量
     * @return
     */
    @Override
    public Map<String, Object> getUserCount() {
        List<UserCountVo> list = baseMapper.selectUserCount();

        Map<String, Object> map = new HashMap<>();
        //日期列表
        List<String> dateList
                =list.stream().map(UserCountVo::getRegisterDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList
                =list.stream().map(UserCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }


}
